package edu.ucsb.cs176b.android;

import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.google.android.c2dm.C2DMBaseReceiver;

public class C2DMReceiver extends C2DMBaseReceiver {
	
	
	public C2DMReceiver() {
		super("ucsb.cs.176b@gmail.com");
	}

	
	public void onRegistered(Context context, String registrationId) throws java.io.IOException {
		Log.e("C2DM", "Registration ID arrived.");
		Log.e("C2DM", registrationId);
	}

	protected void onMessage(Context context, Intent intent) {
		Bundle extras = intent.getExtras();
		if (extras != null) {
            JSONObject jsonRes;
			try {
				jsonRes = new JSONObject((String)extras.get("data"));
				System.out.println("Push msg recieved: " + (String)extras.get("data"));
				
				// Handle REPORT messages
				if(jsonRes.getString("type").toLowerCase().startsWith("report")) {
					JSONObject content = jsonRes.getJSONObject("content");
					String action = content.getString("action") +" Treasure can be seen at: " + content.getString("url");

					MenuMediator.showAlert(action);

				}
				
				//Handle GAMEON messages
				else if(jsonRes.getString("type").toLowerCase().startsWith("gameon")) {
					System.out.println("gamone rec");
					MenuMediator.gameOn();

				
				}
				
				//Handle GAMEOVER messages
				else if(jsonRes.getString("type").toLowerCase().startsWith("gameover")) {
					Intent inte = new Intent("edu.ucsb.cs176b.android.MainMenu");
			    	inte.putExtra("test", "150");
					System.out.println("GAMEOVER recieved");
					sendBroadcast(inte);
				}
				
				
			}
			catch (Exception e) {
				// TODO: handle exception
			}
		}
	}
	
	public void onError(Context context, String errorId) {
		Log.e("C2DM", "Error occured!!!");
	}



}
